﻿using Data;
using Infrastructure.States;
using Logic;
using System;
using UnityEngine;

namespace Hero
{
    public class HeroHealth : MonoBehaviour, IHealth
    {
        public event Action HealthIncreased;
        public event Action HealthDecreased;
        public event Action Destroyed;

        [SerializeField] private HeroShoot _shoot;
        [SerializeField] private HeroReload _reload;
        private GameSceneData _data;
        private HeroState _state;
        private GameStateMachine _stateMachine;

        public int Current
        {
            get => _state.CurrentLives;
            set
            {
                if (value < _state.CurrentLives)
                {
                    _state.CurrentLives = value;
                    HealthDecreased?.Invoke();
                    TakeAwayAmmo();
                    TakeAwayGun();
                    ResetPosition();
                    ClearLoot();
                    ClearBullets();
                }
                else if (value > _state.CurrentLives)
                {
                    _state.CurrentLives = value;
                    HealthIncreased?.Invoke();
                }
            }
        }

        public void Construct(GameSceneData data, HeroState state)
        {
            _data = data;
            _state = state;
        }

        public void TakeDamage(float damage)
        {
            if (Current > 0)
                Current--;
            if (Current <= 0) Die();
        }

        public void Die() =>
            Destroyed?.Invoke();

        private void TakeAwayAmmo()
        {
            if (_state.MaxAmmo <= 1) 
                return;
            _state.MaxAmmo--;
            _reload.ReplenishAmmo();
        }

        private void TakeAwayGun()
        {
            if (_state.CurrentGuns <= 1)
                return;
            _state.CurrentGuns--;
            _shoot.InitGuns();
        }

        private void ResetPosition() =>
            transform.position = _data.HeroSpawnPoint;

        private void ClearLoot() =>
            Utils.Cleanup(_data.LootPieces);

        private void ClearBullets() =>
            Utils.Cleanup(_data.Bullets);
    }
}